package com.mk.admin.schedule;


import com.mk.admin.mapper.DictionaryMapper;
import com.mk.admin.model.dto.DictionaryDto;
import com.mk.admin.model.entity.DictionaryEntity;
import com.mk.admin.model.vo.MedicalTechnologyReportRemoteVo;
import com.mk.admin.service.MedicalTechnologyReportService;
import com.mk.admin.util.DateTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 得到医技预约（检验检查报告），
 * <p>
 * 亦可单独刷新 在医技预约里面
 */
@Configuration
@EnableScheduling
public class TaskGetMedicalTechnologyReport implements SchedulingConfigurer {
    @Autowired
    private DictionaryMapper dictionaryMapper;
    @Autowired
    private MedicalTechnologyReportService medicalTechnologyReportService;
    @Value("${spring.profiles.active}")
    private String dev;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        if ("dev".equals(dev)) {
            return;
        }
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> System.out.println("执行动态定时任务: " + LocalDateTime.now().toLocalTime()),
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    //2.1 从数据库获取执行周期
                    DictionaryEntity entity = new DictionaryEntity();
                    entity.setCode("TaskGetMedicalTechnologyReport");
                    entity.setStatus(1);
                    List<DictionaryDto> list = dictionaryMapper.select(entity);
                    String cron = "0 0 0/1 * * ?";//每小时执行一次
                    Long second = 24 * 60 * 60L;
                    if (list.size() > 0) {
                        DictionaryDto dto = list.get(0);
                        if (dto.getDescribe() != null) {
                            cron = dto.getDescribe();
                        }
                        if (dto.getSecond() != null) {
                            second = dto.getSecond();
                        }
                        MedicalTechnologyReportRemoteVo medicalTechnologyReportRemoteVo = new MedicalTechnologyReportRemoteVo();
                        medicalTechnologyReportRemoteVo.setBeginTime(DateTool.format(-second));
                        medicalTechnologyReportRemoteVo.setEndTime(DateTool.format());
                        medicalTechnologyReportService.check(medicalTechnologyReportRemoteVo);
                    }

                    //2.3 返回执行周期(Date)
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }
}
